package com.scalar.chiptrack.operations.finishedGoods.actionCommands;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.finishedGoods.FinishedGoodsHelper;
import com.scalar.chiptrack.operations.finishedGoods.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.finishedGoods.forms.FinishedGoodsEntryForm;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.dao.VendorLocationDAO;

/**
 * User: Murali Krishna Yengala
 * Date: May 27, 2005
 * Time: 5:09:58 PM
 */
public class FinishedGoodsNewEntrySaveCommand  extends ChipTrackExtendedAction{

    public ActionForward executeRequest( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) throws Exception
    {

        HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
        HttpSession session = request.getSession();

        FinishedGoodsEntryForm finishedGoodsEntryForm = ( FinishedGoodsEntryForm ) form;
        String partNumber = finishedGoodsEntryForm.getFinishedGoodsPartNo() == null ? "" : finishedGoodsEntryForm.getFinishedGoodsPartNo().trim();

        if( !(isTokenValid( request)) )
        {
            errors.put ( "Finished Goods is Already Saved", null );
            FinishedGoodsHelper.setBaseProductsAndCustomers( request, errors);
            request.setAttribute ( SessionKeys.ERROR_MESSAGES , errors );
            return  mapping.findForward("new");
        }
        
        int baseProductId = finishedGoodsEntryForm.getBaseProductIdI();
        int customerId = finishedGoodsEntryForm.getCustomerIdI();

        String[] fgiProcessStepIds = finishedGoodsEntryForm.getFgiProcessStepIds();
        String[] customerIds = finishedGoodsEntryForm.getCustomerIds();
        String description = finishedGoodsEntryForm.getDescription() == null ? "" : finishedGoodsEntryForm.getDescription();
        String programCode = (finishedGoodsEntryForm.getProgramCode() == null ? "" : finishedGoodsEntryForm.getProgramCode().trim());
        String crc = ( finishedGoodsEntryForm.getCrc() == null ? "" : finishedGoodsEntryForm.getCrc().trim());
        String algorithmId = finishedGoodsEntryForm.getAlgorithm();
        String isBlankProduct = finishedGoodsEntryForm.getIsBlankProduct();
        int isApproved = finishedGoodsEntryForm.isApproved() ? 0 : 1;
        ArrayList dupPartNos = finishedGoodsEntryForm.getEquivalentPartNosList();
        ArrayList processParameters = finishedGoodsEntryForm.getParametersList();
        ArrayList selectedVendorLocations = FinishedGoodsHelper.getVendorLocations( request, true);

        DBTransaction dbTransaction = null;
        boolean success = false;

        try
        {
            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();
            // Check for partnumber in Product map table

            int processStepId = ProcessStep.getProcessStepID ( dbTransaction , Constants.LOCATION_TYPE_FINISHED_GOODS , Constants.LOCATION_TYPE_FINISHED_GOODS , description  );
            //System.out.println("NEW ENTRY SAVE, processStepid : " + processStepId );
            FinishedGoodsDAO.saveProcessStepProduct( dbTransaction, processStepId, partNumber, baseProductId, description, isApproved, null , customerId, programCode, algorithmId, crc, isBlankProduct );
            FinishedGoodsDAO.saveFgToFgiMappings( dbTransaction, processStepId, fgiProcessStepIds, baseProductId);
            if( dupPartNos != null && dupPartNos.size() > 0)
            {
                FinishedGoodsDAO.saveProductMap(dbTransaction, processStepId, dupPartNos, selectedVendorLocations );
            }
            FinishedGoodsDAO.saveParameters( dbTransaction, processStepId, processParameters);
            FinishedGoodsDAO.saveCustomersForFG( dbTransaction, processStepId, customerIds );
            if ( ( selectedVendorLocations != null ) && ( selectedVendorLocations.size () > 0 ) )
            {
                VendorLocationDAO.saveVendorLocations ( dbTransaction , processStepId , selectedVendorLocations.iterator () );
            }
            success = true;
        }
        catch ( ScalarException se )
        {
            success = false;
            se.printStackTrace ();
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "");
        }
        catch ( Exception se )
        {
            success = false;
            se.printStackTrace ();
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "");
        }
        finally
        {
            // Rollback or Commit the Transaction
            if ( success == true )
            {
                if ( dbTransaction != null )
                {
                    dbTransaction.commit ();
                }
                session.removeAttribute("finishedGoodsEntryForm");
                resetToken( request);
                info.put ( "Finished Goods = "+partNumber,"Saved Successfully" );
            }
            else
            {
                errors.put ( "Finished Goods = "+partNumber, "Could not save Finished Goods" );
                dbTransaction.rollback ();
            }
        }
        FinishedGoodsHelper.setBaseProductsAndCustomers( request, errors);
        request.setAttribute ( SessionKeys.ERROR_MESSAGES , errors );
        request.setAttribute ( SessionKeys.INFO_MESSAGES , info );
        return  mapping.findForward("new");
    }

}
